package com.milling.framework.websocket;

import com.milling.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AlertConfirmMonitorService {
    private static final String ALERT_ON = "on";
    private static final String ALERT_OFF = "off";

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private AlertConfirmWebSocketHandler webSocketHandler;

    private String lastStatus = ALERT_OFF;

//    @Scheduled(fixedRate = 5000)
    public void monitorAlertStatus() {
        String currentStatus = sysConfigService.getAlertStatus();
        String normalizedCurrent = currentStatus != null ? currentStatus.trim().toLowerCase() : ALERT_OFF;

        if (ALERT_ON.equals(normalizedCurrent)) {
            if (!ALERT_ON.equals(lastStatus)) {
                System.out.println("[" + new Date() + "] 检测到状态变化: off -> on");
            } else {
                System.out.println("[" + new Date() + "] 检测到 config_value 仍为 on");
            }

            String alertMessage = "{\"type\":\"alert\",\"title\":\"报警信息\",\"content\":\"请确认此报警信息\",\"buttons\":{\"confirm\":\"确认\",\"cancel\":\"取消\"}}";
            webSocketHandler.sendAlert(alertMessage);
            System.out.println("[" + new Date() + "] 警报消息已发送");
        }

        if (ALERT_OFF.equals(normalizedCurrent) && !ALERT_OFF.equals(lastStatus)) {
            System.out.println("[" + new Date() + "] 检测到状态变化: on -> off");
        }

        lastStatus = normalizedCurrent;
    }
}
